<?php

require_once dirname(__FILE__).'/../lib/contactGeneratorConfiguration.class.php';
require_once dirname(__FILE__).'/../lib/contactGeneratorHelper.class.php';

/**
 * contact actions.
 *
 * @package    tfe
 * @subpackage contact
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class contactActions extends autoContactActions {
    public function executeShow(sfWebRequest $request) {
        $this->contact = Doctrine::getTable('Contact')->find(array($request->getParameter('id')));

        //Voici comment recuperer les informations contenus dans les tableaux via les relations en BD
        $this->personneStages = $this->contact->getStages();
        $this->personneAbonnement = $this->contact->getAbonnements();
        $this->personneLocation = $this->contact->getLocations();
        $this->personneCommu = $this->contact->getCommunications();
        $this->personneRes = $this->contact->getReservations();
        $this->personneParrain = $this->contact->getFilleulCadeaux();
        $this->personneMails = $this->contact->getEmails();
        $this->personneAteliers = $this->contact->getAteliers();
        $this->personneNewsletters = $this->contact->getNewsletters();
        $this->personneTelephone = $this->contact->getNumerosDeTelephone();
        $this->personneFax = $this->contact->getNumerosDeFax();
        $this->personneCptBanque = $this->contact->getNumerosDeCompteBancaire();

        //$this->stage=Doctrine::getTable('Stage')->find(array($request->getParameter('id')));
        $this->forward404Unless($this->contact);
        $this->form = new EMailForm();

        // ajouter le contact à l'historique
        $this->getUser()->ajouterContactAHistorique($this->contact);
    }


    public function executeListShow(sfWebRequest $request) {
        $this->redirect('contact/show?id='. $request->getParameter('id'));
    }

    public function executeEdit(sfWebRequest $request) {
        parent::executeEdit($request);
        // ajouter à l'historique
        $this->getUser()->ajouterContactAHistorique(Doctrine_Core::getTable('Contact')->find($request->getParameter('id')));
    }


    public function executeAutocomplete(sfWebRequest $request) {
        $this->getResponse()->setContentType('application/json');
        $request = Doctrine::getTable('Contact')->createQuery()
                ->where("nom LIKE ?","%".$request->getParameter('q')."%")
                ->orWhere("prenom LIKE ?","%".$request->getParameter('q')."%")
                ->limit($request->getParameter('limit'))
                ->execute()
                ->getData();

        $contacts = array();
        foreach ( $request as $contact ) {
            $contacts[$contact->id] = (string) $contact;
        }
        return $this->renderText(json_encode($contacts));
    }


    public function executeUpdateMail(sfWebRequest $request) {
        $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
        $this->forward404Unless($email = Doctrine::getTable('Email')->find(array($request->getParameter('id'))), sprintf('Object email does not exist (%s).', $request->getParameter('id')));
        $this->form = new EmailForm($email);

        $this->processForm($request, $this->form);

        $this->setTemplate('edit');
    }

    public function executeCreateMail(sfWebRequest $request) {
        $this->forward404Unless($request->isMethod(sfRequest::POST));

        $this->form = new EmailForm();

        $this->processForm($request, $this->form);

        $this->setTemplate('new');
    }

    // utile pour que les actions batch respecten le softDelete
    protected function executeBatchDelete(sfWebRequest $request) {
        $ids = $request->getParameter('ids');

        $records = Doctrine_Query::create()
                ->select()
                ->from('Contact')
                ->whereIn('id', $ids)
                ->execute();

        $count = 0;
        foreach($records as $record) {
            $count += $record->delete();
        }

        if ($count >= count($ids)) {
            $this->getUser()->setFlash('notice', 'The selected items have been deleted successfully.');
        }
        else {
            $this->getUser()->setFlash('error', 'A problem occurs when deleting the selected items.');
        }

        $this->redirect('@contact');
    }

    public function processForm(sfWebRequest $request, sfForm $form) {

        $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));


        if ($form->isValid()) {
            $notice = $form->getObject()->isNew() ? 'The item was created successfully.' : 'The item was updated successfully.';

            $contact = $form->save();


            // ajouter à l'historique
            $this->getUser()->ajouterContactAHistorique($contact);

            $this->dispatcher->notify(new sfEvent($this, 'admin.save_object', array('object' => $contact)));

            if ($request->hasParameter('_save_and_add')) {
                $this->getUser()->setFlash('notice', $notice.' You can add another one below.');

                $this->redirect('@contact_new');
            }
            else {
                $this->getUser()->setFlash('notice', $notice);

                $this->redirect(array('sf_route' => 'contact_edit', 'sf_subject' => $contact));
            }
        }
        else {
            $this->getUser()->setFlash('error', 'The item has not been saved due to some errors.', false);
        }
    }

    // creation d'un fichier CSV contenant noms + mails des contacts selectionnes
    protected function executeBatchCsvMails(sfWebRequest $request) {
        // creation d'un nom unique de fichier sur base d'un hashage de la concaténation du nom d'utilisateur et d'un timestamp
        // puis appelle à la méthode objet
        $filename = sha1($this->getUser().date('ymd').time()).'.csv';
        Contact::createCsvMails($request->getParameter('ids'),$filename);

        // redirection vers telechargement du fichier CSV genere
        $this->redirect('CSV/mails?filename='.$filename);
    }

    // creation d'un fichier CSV contenant noms + adresses des contacts selectionnes
    protected function executeBatchCsvLettres(sfWebRequest $request) {
        // creation d'un nom unique de fichier sur base d'un hashage de la concaténation du nom d'utilisateur et d'un timestamp
        // puis appelle à la méthode objet
        $filename = sha1($this->getUser().date('ymd').time()).'.csv';
        Contact::createCsvLettres($request->getParameter('ids'),$filename);

        // redirection vers telechargement du fichier CSV genere
        $this->redirect('CSV/lettres?filename='. $filename);
    }

    // ACTIONS JSON
    // trouver les inscriptions stages pour un contact predefini
    // on prend le libelle, le nom de l'anim, type artistique, la date d'inscription
    public function executeTrouverInsStage(sfWebRequest $request) {
        $inscriptions = array();
        if ($request->isXmlHttpRequest()) {
            if (!is_null($request->getParameter('id'))) {
                $contact = Doctrine::getTable('Contact')->find(array($request->getParameter('id')));

                if (!is_null($contact) && !empty($contact)) {
                    $insStage = $contact->getStages();
                    foreach ($insStage as $stage) {
                        $libelle = $stage->getStage()->getLibelle();
                        $typeArt = $stage->getStage()->getTypeArtistique()->getLibelle();
                        $animateur = $stage->getStage()->getAnimateur()->getNom()." ".$stage->getStage()->getAnimateur()->getPrenom();
                        $inscriptions['cellule'][] = array(
                                'id'   => $stage->getId(),
                                'cell' => array($libelle, $typeArt, $animateur)
                        );
                    }
                    $this->getResponse()->setHttpHeader('Content-Type','application/json; charset=utf-8');
                    $inscriptions = $this->renderText(json_encode($inscriptions));
                } else {
                    throw new Exception("Valeur de contact non valide : ".$contact);
                }
            }
        }

        // encoder en Jason78 Ouuuuais big up, snoop dogg .. snoop doggy dog !
        return $inscriptions;
    }

    // trouver tous les ateliers auxquels est inscrit un contact
    // libelle, animateur, type artistique, date d'inscription
    public function executeTrouverInsAtelier(sfWebRequest $request) {
        $inscriptions = array();
        if ($request->isXmlHttpRequest()) {
            if (!is_null($request->getParameter('id'))) {
                $contact = Doctrine::getTable('Contact')->find(array($request->getParameter('id')));

                if (!is_null($contact) && !empty($contact)) {
                    $insAtelier = $contact->getAteliers();
                    foreach ($insAtelier as $atelier) {
                        $libelle = $atelier->getAtelier()->getLibelle();
                        $typeArt = $atelier->getAtelier()->getTypeArtistique()->getLibelle();
                        $animateur = $atelier->getAtelier()->getAnimateur()->getNom()." ".$atelier->getAtelier()->getAnimateur()->getPrenom();
                        $inscriptions['cellule'][] = array(
                                'id'        => $atelier->getId(),
                                'cell'      => array($libelle, $typeArt, $animateur)
                        );

                    }
                    $this->getResponse()->setHttpHeader('Content-Type','application/json; charset=utf-8');
                    $inscriptions = $this->renderText(json_encode($inscriptions));
                }
            }
        }

        // encoder en Jason78 Ouuuuais big up, snoop dogg .. snoop doggy dog !
        return $inscriptions;
    }

    // trouver tous les parrainages pour un contact
    public function executeTrouverParrainages(sfWebRequest $request) {
        $inscriptions = array();
        if ($request->isXmlHttpRequest()) {
            if (!is_null($request->getParameter('id'))) {
                $contact = Doctrine::getTable('Contact')->find(array($request->getParameter('id')));

                if (!is_null($contact) && !empty($contact)) {
                    $parrains = $contact->getFilleulCadeaux();
                    foreach ($parrains as $parrain) {
                        $inscriptions['cellule'][] = array(
                                'id'        => $parrain->getContact()->getId(),
                                'cell'      => array($parrain->getContact()->getNom(),$parrain->getContact()->getPrenom())
                        );

                    }
                    $this->getResponse()->setHttpHeader('Content-Type','application/json; charset=utf-8');
                    $inscriptions = $this->renderText(json_encode($inscriptions));
                }
            }
        }

        // encoder en Jason78 Ouuuuais big up, snoop dogg .. snoop doggy dog !
        return $inscriptions;
    }

    // trouver toutes les reservations pour un contact
    public function executeTrouverReservations(sfWebRequest $request) {
        $inscriptions = array();
        if ($request->isXmlHttpRequest()) {
            if (!is_null($request->getParameter('id'))) {
                $contact = Doctrine::getTable('Contact')->find(array($request->getParameter('id')));

                if (!is_null($contact) && !empty($contact)) {
                    $reservations = $contact->getReservations();
                    foreach ($reservations as $reservation) {
                        $date = explode("-",$reservation->getEvenement()->getDate());
                        $inscriptions['cellule'][] = array(
                                'id'        => $reservation->getEvenement()->getId(),
                                'cell'      => array($reservation->getEvenement()->getLibelle(),$date[2]."-".$date[1]."-".$date[0])
                        );

                    }
                    $this->getResponse()->setHttpHeader('Content-Type','application/json; charset=utf-8');
                    $inscriptions = $this->renderText(json_encode($inscriptions));
                }
            }
        }

        return $inscriptions;
    }

    public function executeTrouverNewsletters(sfWebRequest $request) {
        $inscriptions = array();
        if ($request->isXmlHttpRequest()) {
            if (!is_null($request->getParameter('id'))) {
                $contact = Doctrine::getTable('Contact')->find(array($request->getParameter('id')));

                if (!is_null($contact) && !empty($contact)) {
                    $newsletters = $contact->getNewsletters();
                    foreach ($newsletters as $newsletter) {
                        $inscriptions['cellule'][] = array(
                                'id'        => $newsletter->getId(),
                                'cell'      => array($newsletter->getLibelle(),$newsletter->getCommentaire())
                        );

                    }
                    $this->getResponse()->setHttpHeader('Content-Type','application/json; charset=utf-8');
                    $inscriptions = $this->renderText(json_encode($inscriptions));
                }
            }
        }

        return $inscriptions;
    }

    public function executeTrouverLocations(sfWebRequest $request) {
        $inscriptions = array();
        if ($request->isXmlHttpRequest()) {
            if (!is_null($request->getParameter('id'))) {
                $contact = Doctrine::getTable('Contact')->find(array($request->getParameter('id')));

                if (!is_null($contact) && !empty($contact)) {
                    $locations = $contact->getLocations();
                    foreach($locations as $location) {
                        foreach ($location->getSalles() as $salles) {
                            $inscriptions['cellule'][] = array(
                                    'id'        => $salles->getId(),
                                    'cell'      => array($salles->getLibelle())
                            );
                        }
                    }
                    $this->getResponse()->setHttpHeader('Content-Type','application/json; charset=utf-8');
                    $inscriptions = $this->renderText(json_encode($inscriptions));
                }
            }
        }

        return $inscriptions;
    }

    public function executeTrouverCommunications(sfWebRequest $request) {
        $inscriptions = array();
        if ($request->isXmlHttpRequest()) {
            if (!is_null($request->getParameter('id'))) {
                $contact = Doctrine::getTable('Contact')->find(array($request->getParameter('id')));

                if (!is_null($contact) && !empty($contact)) {
                    $communications = $contact->getCommunications();
                    foreach ($communications as $communication) {
                        $date = explode("-",$communication->getDate());
                        $inscriptions['cellule'][] = array(
                                'id'        => $communication->getId(),
                                'cell'      => array($communication->getObjet(),$date[2]."-".$date[1]."-".$date[0], $communication->getCommentaire())
                        );

                    }
                    $this->getResponse()->setHttpHeader('Content-Type','application/json; charset=utf-8');
                    $inscriptions = $this->renderText(json_encode($inscriptions));
                }
            }
        }

        return $inscriptions;
    }

    public function executeTrouverInsAbonnements(sfWebRequest $request) {
         $inscriptions = array();
        if ($request->isXmlHttpRequest()) {
            if (!is_null($request->getParameter('id'))) {
                $contact = Doctrine::getTable('Contact')->find(array($request->getParameter('id')));

                if (!is_null($contact) && !empty($contact)) {
                    $abos = $contact->getAbonnements();
                    foreach ($abos as $abo) {
                        $inscriptions['cellule'][] = array(
                                'id'        => $abo->getIdAbonnement(),
                                'cell'      => array($abo->getAbonnement()->getLibelle(), $abo->getAbonnement()->getSaison())
                        );

                    }
                    $this->getResponse()->setHttpHeader('Content-Type','application/json; charset=utf-8');
                    $inscriptions = $this->renderText(json_encode($inscriptions));
                }
            }
        }

        return $inscriptions;
    }


    public function executeInscrireAuxNewsMail(sfWebRequest $request){
        //todo
    }
}
